package com.hex.ds.hdrs.cron.service;

import com.hex.ds.hdrs.agent.service.AgentManager;
import com.hex.ds.hdrs.agent.service.AgentSession;
import com.hex.ds.hdrs.app.service.AppManager;
import com.hex.ds.hdrs.app.service.AppSession;
import com.hex.ds.hdrs.common.constant.Const;
import com.hex.ds.hdrs.common.utils.HdrsDateUtil;
import com.hex.ds.hdrs.cron.po.CronTask;
import com.hex.ds.hdrs.period.task.po.PeriodTask;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 定时任务重跑
 */
@Service
@Slf4j
public class CronTaskReRunService {

	@Autowired
	private CronTaskService cronTaskService;
	@Autowired
	private AppManager appManager;
	@Autowired
	private AgentManager agentManager;

	public void reRunTask(List<String> pkIds) {
		if (CollectionUtils.isNotEmpty(pkIds)) {
			try {
				for (String pkId : pkIds) {
					CronTask cronTask = new CronTask();
					cronTask.setPkId(pkId);
					List<CronTask> list = cronTaskService.qryTaskList(cronTask);
					//先更新下执行开始时间
					cronTask.setExecStTs(HdrsDateUtil.getCurTs());
		            cronTask.setUpTs(HdrsDateUtil.getCurTs());
		            cronTask.setExecStatus(Const.CRON_TASK_EXEC_STATUS_EXECING);
		            cronTask.setExecFailReason(null);
		            cronTaskService.updateCronTask(cronTask);
					CronTask cronTask2 = list.get(0);
					PeriodTask task = new PeriodTask();
					task.setAppCode(cronTask2.getAppCode());
					task.setResNum(0);
					task.setAppointAgentCode(cronTask2.getAppointAgentCode());
					AppSession appSession = appManager.getValidAppSession(cronTask2.getAppCode());
					AgentSession agentSession = appSession.getFitAgent(agentManager, null, task);
					cronTask2.setAgentCode(agentSession.getAgentCode());
					agentSession.sendCronToAgent(cronTask2);
				}
			} catch (Exception e) {
				log.error("定时任务重跑出错:{}" , e.getMessage(), e);
			}
		}
	}

}
